const apilive = "https://api.live.bilibili.com/room/v1/Room/get_info?room_id=";
const apimaster = "https://api.live.bilibili.com/live_user/v1/Master/info?uid=";

const fs = require('fs');
const uidPath = '../data/uid.json';
const dataPath = '../data/data.json';

// 使用 IIFE 包裹所有需要使用 await 的代码
(async () => {
    try {
        // 动态导入 node-fetch 模块
        const fetch = (await import('node-fetch')).default;

        class User {
            constructor(uid) {
                this.uid = uid;
                this.roomid = null;
                this.title = null; //直播间标题
                this.user_cover = null;//直播间封面url
                this.live_time = null;//开播时间
                this.area_name = null;//子分区名字
                this.live_status = null; //直播状态，0未开播，1开播中，2轮播中

                this.uname = null;//主播用户名(info中)
                this.face = null;//主播头像url(info中)
                this.follower_num = null;//粉丝数
                this.medal_name = null;//粉丝勋章名
                this.getData();
            }

            async getData() {
                try {
                    let jsonMasterData = await this.getMasterInfo(this.uid);
                    await this.loadMasterInfo(jsonMasterData);
                    let jsonLiveData = await this.getLiveInfo(this.roomid);
                    await this.loadLiveInfo(jsonLiveData);
                } catch (error) {
                    console.error('Initialization error:', error);
                }
            }

            getLiveInfo(roomid) {
                return fetch(`${apilive}${roomid}`)
                    .then(response => {
                        if (!response.ok) {
                            throw new Error(`HTTP error! Status: ${response.status}`);
                        }
                        return response.json();
                    })
                    .then(data => {
                        if (data.code !== 0) throw new Error(data.message);
                        return data;
                    })
                    .catch(error => {
                        console.error('Error fetching live info:', error);
                        throw new Error(`Failed to fetch live info for room ID ${roomid}: ${error.message}`);
                    });
            }

            loadLiveInfo(jsonLiveData) {
                const data = jsonLiveData.data;
                this.title = data.title;
                this.user_cover = data.user_cover;
                this.live_time = data.live_time;
                this.area_name = data.area_name;
                this.live_status = data.live_status;
            }

            getMasterInfo(uid) {
                return fetch(`${apimaster}${uid}`)
                    .then(response => {
                        if (!response.ok) {
                            throw new Error(`HTTP error! Status: ${response.status}`);
                        }
                        return response.json();
                    })
                    .then(data => {
                        if (data.code !== 0) throw new Error(data.message);
                        return data;
                    })
                    .catch(error => {
                        console.error('Error fetching master info:', error);
                        throw new Error(`Failed to fetch master info for UID ${uid}: ${error.message}`);
                    });
            }

            loadMasterInfo(jsonMasterData) {
                const data = jsonMasterData.data;
                this.uid = data.info.uid;
                this.uname = data.info.uname;
                this.face = data.info.face;
                this.roomid = data.room_id;
                this.follower_num = data.follower_num;
                this.medal_name = data.medal_name;
            }
        }

        let updateData = [];

        // 读取UID文件并处理用户数据
        const jsonData = JSON.parse(fs.readFileSync(uidPath, 'utf8'));
        const userPromises = jsonData.uids.map(async (uid) => {
            const user = new User(uid);
            // 等待User实例初始化完成
            await user.getData();  // 注意：这里可能需要调整，因为getData已经在构造函数中被调用了。
            return {
                uid: user.uid,
                roomid: user.roomid,
                title: user.title,
                user_cover: user.user_cover,
                live_time: user.live_time,
                area_name: user.area_name,
                live_status: user.live_status,
                uname: user.uname,
                face: user.face,
                follower_num: user.follower_num,
                medal_name: user.medal_name
            };
        });

        // 等待所有的User实例初始化完成，并收集结果
        updateData = await Promise.all(userPromises);

        // 写入data.json
        fs.writeFileSync(dataPath, JSON.stringify(updateData, null, 2), 'utf8');
        console.log("Data has been written to data.json");

    } catch (error) {
        console.error("Error:", error);
    }
})();